﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using TierApplication;
using System.Text.RegularExpressions;

public partial class ForeProgram_shopCartView : System.Web.UI.Page
{
    #region Page_Load
    /// <summary>
    /// Page_Load
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Load();
            TotalCart();
        }
        //UGridView gv = new UGridView(gvTable);
    }
    #endregion

    #region 加载数据
    /// <summary>
    /// 加载数据
    /// </summary>
    private void Load()
    {
        T_CART cart = new T_CART();
        string strWhere = " And accountid='" + Security.GetAccountId() + "'";
        gvTable.DataSource = cart.GetCartByWhere(strWhere).Tables[0];
        gvTable.DataBind();
    }
    #endregion

    #region 事件
    protected void gvTable_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItemIndex == -1) return;
        Image imgProduct = (Image)e.Row.FindControl("imgProduct");
        HyperLink hlProduct = (HyperLink)e.Row.FindControl("hlProduct");
        imgProduct.ImageUrl = "~/ProductImages/" + DataBinder.Eval(e.Row.DataItem, "productimage").ToString();
        imgProduct.ToolTip = DataBinder.Eval(e.Row.DataItem, "Productname").ToString();
        hlProduct.NavigateUrl = "ProductView.aspx?productid=" + DataBinder.Eval(e.Row.DataItem, "productid").ToString();
        hlProduct.Text = DataBinder.Eval(e.Row.DataItem, "Productname").ToString();
        TextBox Count = (TextBox)e.Row.FindControl("proCount");
        Count.Text = DataBinder.Eval(e.Row.DataItem, "quantity").ToString();
        ImageButton Sub = (ImageButton)e.Row.FindControl("imgSub");
        ImageButton Add = (ImageButton)e.Row.FindControl("imgAdd");
        Sub.CommandArgument = e.Row.RowIndex.ToString();
        Add.CommandArgument = e.Row.RowIndex.ToString();
    }
    protected void imgClear_Click(object sender, ImageClickEventArgs e)
    {
        T_CART cart = new T_CART();
        if (cart.DeleteByAccountid(Security.GetAccountId()))
        {
            Load();
            TotalCart();
        }
        else
        {
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), DateTime.Now.ToLongTimeString(), "<script>alert('清空失败！');</script>");
        }
    }
    protected void imgOrder_Click(object sender, ImageClickEventArgs e)
    {
        if (gvTable.Rows.Count == 0)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), DateTime.Now.ToLongTimeString(), "alert('购物车为空！请先放入货物！');swithBtn('display');",true);
            return;
        }
        T_CART cart=new T_CART();
        List<T_CART> list=new List<T_CART>();
        for (int i = 0; i < gvTable.Rows.Count; i++)
        {
            T_CART ent = new T_CART();
            ent.CARTID = gvTable.DataKeys[i].Values[0].ToString();
            ent.PRODUCTID = gvTable.DataKeys[i].Values[1].ToString();
            ent.QUANTITY = Convert.ToDecimal(((TextBox)gvTable.Rows[i].FindControl("proCount")).Text);
            ent.UNITPRICE = Convert.ToDecimal(gvTable.Rows[i].Cells[3].Text);
            list.Add(ent);
        }
        if (cart.UpdateCartList(list))
        {
            Page.Response.Redirect("shopAddOrder.aspx");
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), DateTime.Now.ToLongTimeString(), "alert('跳转失败！');swithBtn('display');", true);
        }
    }
    protected void gvTable_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        T_CART cart = new T_CART();
        string cartid = gvTable.DataKeys[e.RowIndex].Values["cartid"].ToString();
        if (cart.Delete(cartid))
        {
            Load();
            TotalCart();
        }
        else
        {
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), DateTime.Now.ToLongTimeString(), "<script>alert('跳转失败！');</script>");
        }
    }

    protected void gvTable_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        T_CART cart = new T_CART();
        T_CART ent = new T_CART();
        int index = Convert.ToInt32(e.CommandArgument);
        TextBox Count = (TextBox)gvTable.Rows[index].FindControl("proCount");
        string cartid = gvTable.DataKeys[index].Values["cartid"].ToString();
        string productid = gvTable.DataKeys[index].Values["productid"].ToString();
        switch (e.CommandName)
        {
            case "sub":
                ent.CARTID = cartid;
                bool check=CheckProduct(productid, (Convert.ToInt32(Count.Text) - 1).ToString());
                if (check)
                    ent.QUANTITY = Convert.ToInt32(Count.Text) - 1;
                else
                    ent.QUANTITY = 1;
                if (cart.UpdateCartCount(ent))
                {
                    if(check)
                        Count.Text = (Convert.ToInt32(Count.Text) - 1).ToString();
                    else
                        Count.Text = "1";
                }
                break;
            case "add":
                ent.CARTID = cartid;
                bool check2 = CheckProduct(productid, (Convert.ToInt32(Count.Text) + 1).ToString());
                if (check2)
                    ent.QUANTITY = Convert.ToInt32(Count.Text) + 1;
                else
                    ent.QUANTITY = 1;
                if (cart.UpdateCartCount(ent))
                {
                    if (check2)
                        Count.Text = (Convert.ToInt32(Count.Text) + 1).ToString();
                    else
                        Count.Text = "1";
                }
                break;
            default:
                break;
        }
        TotalCart();
    }
    #endregion

    #region 检验商品数量
    /// <summary>
    /// 检验商品数量
    /// </summary>
    /// <param name="product"></param>
    /// <param name="sl"></param>
    /// <returns></returns>
    private bool CheckProduct(string product,string sl)
    {
        Regex rg = new Regex("^([0-9]*)$");
        if (!rg.Match(sl).Success)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), DateTime.Now.ToLongTimeString(), "alert('请输入正确的数字！');", true);
            return false;
        }
        int count = Convert.ToInt32(sl);
        if(count<=0)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), DateTime.Now.ToLongTimeString(), "alert('数量不能小于1，请删除此货物！');", true);
            return false;
        }
        if (count > 10)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), DateTime.Now.ToLongTimeString(), "alert('修改数量失败！');", true);
            return false;
        }
        if (count > GetProductCount(product))
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), DateTime.Now.ToLongTimeString(), "alert('库存不足，请重新填写数量！');", true);
            return false;
        }
        return true;
    }
    #endregion

    #region 统计购物车
    /// <summary>
    /// 统计购物车
    /// </summary>
    private void TotalCart()
    {
        Clear();
        if (gvTable != null)
        {
            decimal amount = 0;
            int count = 0;
            for (int i = 0; i < gvTable.Rows.Count; i++)
            {
                TextBox Count = (TextBox)gvTable.Rows[i].FindControl("proCount");
                string price = gvTable.Rows[i].Cells[3].Text;
                amount += Convert.ToInt32(Count.Text) * Convert.ToDecimal(price);
                count += Convert.ToInt32(Count.Text);
            }
            lblTotal.Text = "￥" + amount.ToString();
            lblCount.Text = count.ToString();
            //lblTotal.Text = lblAmount.Text;
        }
    }
    #endregion

    #region 清空
    private void Clear()
    {
        //lblAmount.Text = "￥0.00";
        lblCount.Text = "0";
        //lblFavorable.Text = "￥0.00";
        lblTotal.Text = "￥0.00";
        //lblWeight.Text = "0 kg";
    }
    #endregion

    #region 取得商品数量
    /// <summary>
    /// 取得商品数量
    /// </summary>
    /// <param name="productid"></param>
    /// <returns></returns>
    private int GetProductCount(string productid)
    {
        string strWhere = " And productid='" + productid + "'";
        strWhere += " And productitemstatus='1'";
        T_PRODUCTITEM ent = new T_PRODUCTITEM();
        return ent.GetProductCount(strWhere);
    }
    #endregion

    #region 商品修改
    /// <summary>
    /// 商品修改
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void proCount_TextChanged(object sender, EventArgs e)
    {
        T_CART cart = new T_CART();
        T_CART ent = new T_CART();
        TextBox t = (TextBox)sender;
        GridViewRow drv = (GridViewRow)t.NamingContainer;
        int rowIndex = drv.RowIndex;
        string cartid = gvTable.DataKeys[rowIndex].Values["cartid"].ToString();
        string productid = gvTable.DataKeys[rowIndex].Values["productid"].ToString();
        ent.CARTID = cartid;
        bool check = CheckProduct(productid, t.Text);
        if (check)
            ent.QUANTITY = Convert.ToInt32(t.Text);
        else
            ent.QUANTITY = 1;
        if (cart.UpdateCartCount(ent))
        {
            if (!check)
                t.Text = "1";
        }
        TotalCart();
    }
    #endregion
}